from ..models import Grained

class FileterUserAuth():
    '''过滤重复权限'''

    def fileter_userAuth(self, val):
        # 过滤重复权限
        basic_grained = eval(val[0])
        for grained in val[1:]:
            for parent_key, parent_value in eval(grained).items():
                for key, value in parent_value.items():
                    if value == '1':
                        basic_grained.get(parent_key)[key] = value
                    if type(value) is list:
                        list_union = list(set(basic_grained.get(parent_key)[key]).union(set(value)))
                        basic_grained.get(parent_key)[key] = list_union
        return basic_grained

    def to_instance(self, params):
        # 返回过滤后的实际权限

        permisstion = []
        for auth_group_name in params:
            instance = Grained.objects.filter(auth_group=auth_group_name).values('permissions').first()
            if instance is not None:
                permisstion.append(instance.get('permissions'))
        if len(permisstion) <= 0:
            return permisstion

        return self.fileter_userAuth(permisstion)